import hashlib
import os
import random
import time

from django.core.cache import cache, caches
from django.core.paginator import Paginator
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, redirect
from django.template import loader
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt

from App.models import Students, Grade
from App.models import Student as St
from Template.models import Student, Customer, Goods, UserModel
from Template.models import Student, Customer, Goods


def HelloTemplate(request):
    return HttpResponse("<h1/>Hello Template</h1>")


# 模版手动渲染
def index(request):
    # return render(request,'index.html')
    temp = loader.get_template('index.html')
    content = temp.render()
    return HttpResponse(content)


def get_students(request):
    students = Students.objects.all()
    # 当查询为空时，for循环显示为空，使用empty设置默认值
    # students = Students.objects.all().filter(s_name='Socker')
    # for循环中使用forloop.counter可以显示第几次循环
    # for 循环中forloop.first 判断第一个;forloop.last判断最后一个,对其进行操作
    # ifequal 等于比较  { % ifequal forloop.counter 5 %} < listyle = "color: #00ffff" > {{student.get_name}} </li> { % endifequal %}
    # 过滤器 |
    # 单行注释 {# 注释 #}
    # 多行注释 comment
    '''
    {% comment %}
        - 乘除
        {% widthratio 数 分母 分子 %}
        <h4>计算{{ count }}</h4>
        <h4>乘法：{% widthratio  count 1 5 %}</h4>
        <h4>除法：{% widthratio  count 5 1 %}</h4>
        <h4>整除：{% if forloop.counter|divisibleby:2 %} 
        # ifequal 等于比较  { % ifequal forloop.counter 5 %} < listyle = "color: #00ffff" > {{student.get_name}} </li> { % endifequal %}
        <h4>加法：{{ count | add:2  }}</h4>
        <h4>减法：{{ count | add:-2  }}</h4>
        <h3>转换成小写{{ students.0.s_name|lower }}</h3>
        <h3>转换成大写{{ students.0.s_name|upper }}</h3>
        拼接    {{student | join '='}}
        赋值    {{ var | default "cat" }}
        被整除    {% if forloop.counter|divisibleby:2 %}
        日期时间格式化 {{ datevalue | date'yy-mm-dd'}}
    {% endcomment %}
    '''
    context = {
        'students': students,
        'socks': 56,
        'link': "<a href='https://wwww.baidu.com'>百度</a>",
    }
    return render(request, 'Students.html', context=context)


# 模板继承
def home(request):
    return render(request, 'home.html', context={'title': 'home'})


def home_main(request):
    return render(request, 'home_main.html')


# url测试
def students(request, g_id):
    print(g_id)
    students = Students.objects.filter(s_grade=g_id)
    return render(request, 'student_list.html', context=locals())


def grades(request):
    grades = Grade.objects.all()
    for grade in grades:
        print(grade.g_name, grade.id)
    return render(request, 'grade_list.html', context=locals())


def get_date(request, year, month, day):
    print(year, month, day)
    return HttpResponse("当前日期:%s-%s-%s" % (year, month, day))


def learn(request):
    return HttpResponse("我爱学习！")


def url_resolver(request):
    return render(request, 'url_resolver.html')


def get_time(request, hour, minute, second):
    return HttpResponse("当前时间:%s-%s-%s" % (hour, minute, second))


def have_request(request):
    print(request.path)  # /Template/haverequest/
    print(request.body)  # b''
    print(request.encoding)  # None
    print(request.COOKIES)  # {}
    print(request.POST)  # <QueryDict: {}>
    print(request.GET)  # <QueryDict: {}>   | <QueryDict: {'hobby': ['coding', 'sleeping', 'eating']}>
    print(request.GET.values())  # <generator object MultiValueDict.values at 0x0000029B089141A8>
    print(request.GET.get('hobby'))  # 默认获取最后一个  eating
    print(request.GET.getlist('hobby'))  # 获取全部，返回一个列表 ['coding', 'sleeping', 'eating']
    # print(request.META) # 打印所有信息
    for key, value in request.META.items():
        print(key, ":", value)
    return HttpResponse("Request Success")


def create_student(request):
    return render(request, 'create_student.html')


def do_create_student(request):
    print(request.method)
    username = request.POST.get('username')
    print(username)
    return HttpResponse(username)


def resp(request):
    response = HttpResponse()
    response.content = '我还会回来的'  # 直接返回文本
    response.write('我的锅呢')  # 在content后增加内容
    response.flush()  # 清空HttpResponse实例的内容
    return response


def rdirect(request):
    n = random.randint(1, 10)
    if n > 5:
        return HttpResponse("被喜羊羊偷了")
    else:
        url = reverse('tmp:resp')
        # return HttpResponse("被懒羊羊偷了")     #  直接返回文字
        # return HttpResponseRedirect('/Template/resp') # 硬编码直接返回链接
        # return HttpResponseRedirect(url)
        return redirect(url)


def resjson(request):
    date = {
        'Platform': "Windows",
        'code': 200
    }
    return JsonResponse(data=date)


def set_cookie(request):
    response = HttpResponse("设置cookie")
    response.set_cookie('username', 'Jack')
    return response


def get_cookie(request):
    username = request.COOKIES.get('username')
    return HttpResponse(username)


def login(request):
    return render(request, 'login.html')


def do_login(request):
    uname = request.POST.get("uname")
    print(uname)
    response = HttpResponseRedirect(reverse('tmp:mine'))
    # response.set_cookie('uname', uname)
    # response.set_cookie('uname', uname,max_age=60)     # 增加cookie时间,max_age超时时间单位s
    response.set_signed_cookie('base', uname, '1024', max_age=30)
    return response


def mine(request):
    # uname = request.COOKIES.get('uname')发热nh69ki8l9;p[、
    try:
        uname = request.get_signed_cookie('base', salt='1024')
        if uname:
            # return HttpResponse(uname)
            return render(request, 'mine.html', context={"uname": uname})
    except Exception as e:
        print("获取失败")
    return redirect(reverse('tmp:login'))


def do_logout(request):
    response = redirect(reverse('tmp:login'))
    response.delete_cookie('base')
    return response


def slogin(request):
    if request.method == "GET":
        return render(request, 'slogin.html')
    elif request.method == "POST":
        username = request.POST.get('username')
        request.session['username'] = username
        return HttpResponse('登陆成功')


def smine(request):
    username = request.session.get('username')
    print(username)
    # return HttpResponse(username)
    return render(request, 'smine.html', context=locals())


def slogout(request):
    response = redirect(reverse('tmp:smine'))
    # response.delete_cookie("sessionid")  # 只删除session
    # del request.session["username"]     # 只删除cookie
    request.session.flush()  # session和cookie一起删除
    return response


def register(request):
    if request.method == "GET":
        return render(request, 'student_register.html')
    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        print("======", username, password)
        try:
            student = Student()
            student.s_name = username
            student.s_password = password
            student.save()
        except Exception as e:
            return redirect(reverse('tmp:register'))
        return HttpResponse("注册成功")


def sutdent_login(request):
    if request.method == "GET":
        return render(request, 'student_login.html')
    elif request.method == "POST":
        print(request.POST.get('username'))
        username = request.POST.get('username')
        password = request.POST.get('password')
        students = Student.objects.filter(s_name=username).filter(s_password=password)
        if students.exists():
            student = students.first()
            ip = request.META.get("REMOTE_ADDR")
            token = generate_token(ip, username)
            print(token)
            student.s_token = token
            student.save()
            # cookie登录
            # response = HttpResponse("登陆成功")
            # response.set_cookie("token", token)
            #     return response
            # return redirect(reverse("tmp:student_login"))

            # json登录
            date = {
                "status": 200,
                "msg": "登陆成功",
                "token": token
            }
            return JsonResponse(data=date)
        date = {
            "status": 800,
            "msg": "登陆失败"
        }
        return JsonResponse(data=date)


def generate_token(ip, username):
    c_time = time.ctime()
    return hashlib.new("md5", (ip + username + c_time).encode('utf-8')).hexdigest()


def student_mine(request):
    token = request.COOKIES.get("token")  # 拿到token进行校验
    try:
        student = Student.objects.get(s_token=token)
    except Exception as e:
        return redirect(reverse("tmp:student_login"))
    # return HttpResponse(student.s_name)
    # json登录
    date = {
        "status": 200,
        "msg": "OK",
        "date": {
            "username": student.s_name
        }
    }
    return JsonResponse(data=date)


def add_customer(request):
    c_name = request.GET.get("cname")
    customer = Customer()
    customer.c_name = c_name
    customer.save()
    return HttpResponse("添加用户%s成功" % customer.c_name)


def add_goods(request):
    g_name = request.GET.get('gname')
    goods = Goods()
    goods.g_name = g_name
    goods.save()
    return HttpResponse("添加商品%s成功" % goods.g_name)


# 添加购物车
def add_to_cart(request):
    # 一个用户
    customer = Customer.objects.last()
    # 一个商品
    goods = Goods.objects.last()
    # 商品被用户购买
    # goods.g_customer.add(customer)
    # goods.g_customer.remove(customer) # 删除单个
    # 用户购买商品
    customer.goods_set.add(goods)
    return HttpResponse("添加购物车成功")


def get_goods_list(request, customerid):
    print(customerid)
    customer = Customer.objects.get(pk=customerid)
    goodlist = customer.goods_set.all()
    return render(request, 'goods_list.html', context=locals())


def uploadfile(request):
    if request.method == 'GET':
        return render(request, 'upload_file.html')
    elif request.method == "POST":
        icon = request.FILES.get('icon')
        print(icon)
            for part in icon.chunks():
                file.write(part)
                file.flush()
        return HttpResponse("文件上传成功")
